package com.springboot.service;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.math.BigDecimal;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Map;

import java.util.Calendar;

import java.util.Collections;

import java.util.Date;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import com.springboot.dao.FurnitureMapper;

import com.springboot.entity.Furniture;

import com.springboot.entity.FurnitureExample;

import com.springboot.entity.*;
import com.springboot.dao.*;
import com.springboot.entity.Category;

import com.springboot.entity.CategoryExample;

import com.springboot.dao.CategoryMapper;

import com.springboot.dao.FurniturepinglunMapper;
import com.springboot.entity.FurniturepinglunExample;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.multipart.MultipartFile;

@Service

public class FurnitureService implements FurnitureServiceImp {


    private static final Log logger = LogFactory.getLog(FurnitureService.class);

    @Autowired
    private FurnitureMapper furnituredao;
// 定义categorydao参数  


    @Autowired
    private CategoryMapper categorydao; // 定义FurniturepinglunMapper


    @Autowired
    private FurniturepinglunMapper furniturepinglundao;


    //定义方法addfurniture,响应控制层addfurniture请求

    public void addfurniture(HttpServletRequest request, HttpSession session) {

        //输出日志，当前执行方法为addfurniture

        logger.debug("FurnitureService.addfurniture ......");

// 定义 example1为 CategoryExample的实例

        CategoryExample example1 = new CategoryExample();

// 定义categoryall的List使用 categorydao的selectByExample方法查询所有家具数据

        List categoryall = categorydao.selectByExample(example1);

        // 将上面查询到的家具数据保存到request中，返回页面

        request.setAttribute("categoryall", categoryall);


    }


    //定义addfurnitureact方法

    public void addfurnitureact(HttpServletRequest request, HttpSession session, Furniture furniture, MultipartFile imgfile) throws IOException {

        //输出当前方法日志，表示正在执行FurnitureService.addfurnitureact方法

        logger.debug("FurnitureService.addfurnitureact ......");

// 判断图片文件是否为空  

        if (!imgfile.isEmpty()) {

// 调用uploadUtile方法将页面传入的图片文件上传到服务器，将返回的文件名保存到img参数中  

            String img = uploadUtile(imgfile, request);

// 将furniture的图片设置为img的值  

            furniture.setImg(img);

        }


        //使用furnituredao的insert方法将家具添加到数据库中

        furnituredao.insert(furniture);


        //将添加家具信息添加到request中用message参数进行保存

        request.setAttribute("message", "添加家具成功");

    } //定义addfurnitureactjson方法

    public void addfurnitureactjson(Furniture furniture) throws IOException {

        //输出当前方法日志，表示正在执行FurnitureService.addfurnitureactjson方法

        logger.debug("FurnitureService.addfurnitureactjson ......");

        //使用furnituredao的insert方法将家具添加到数据库中

        furnituredao.insert(furniture);

    }


    //定义furnituremanage方法响应页面请求

    public void furnituremanage(HttpServletRequest request, HttpSession session) {

        //输出日志，表示当前正在执行FurnitureService.furnituremanage

        logger.debug("FurnitureService.furnituremanage ......");


        //实例化FurnitureExample类为example

        FurnitureExample example = new FurnitureExample();


        //使用  furnituredao.selectByExample(example)方法获取所有的家具数据

        List furnitureall = furnituredao.selectByExample(example);


        //将所有的家具数据保存到request中的furnitureall参数里

        request.setAttribute("furnitureall", furnitureall);


    }


    // 定义 furnitureview方法

    public void furnitureview(HttpServletRequest request, HttpSession session) {

        // 输出日志，表示当前正在执行FurnitureService.furnitureview方法

        logger.debug("FurnitureService.furnitureview ......");


        // 实例化FurnitureExample类

        FurnitureExample example = new FurnitureExample();


        // 使用furnituredao的selectByExample方法查询家具信息

        List furnitureall = furnituredao.selectByExample(example);


        // 将查询的furnitureall保存到request中，记录为参数furnitureall

        request.setAttribute("furnitureall", furnitureall);


    }


    // 定义 updatefurniture方法

    public void updatefurniture(HttpServletRequest request, HttpSession session, int id) {

        // 输出日志FurnitureController.updatefurniture，表示正在执行该方法

        logger.debug("FurnitureController.updatefurniture ......");


        // 定义家具为biaoming，使用 furnituredao的selectByPrimaryKey方法通过id查询数据

        Furniture furniture = furnituredao.selectByPrimaryKey(id);


// 定义 example1为 CategoryExample的实例

        CategoryExample example1 = new CategoryExample();

// 定义categoryall的List使用 categorydao的selectByExample方法查询所有家具数据

        List categoryall = categorydao.selectByExample(example1);

        // 将上面查询到的家具数据保存到request中，返回页面

        request.setAttribute("categoryall", categoryall);


        // 将查询的家具保存到request中

        request.setAttribute("furniture", furniture);


    }


    // 定义updatefurnitureact处理家具修改

    public void updatefurnitureact(HttpServletRequest request, Furniture furniture, HttpSession session, MultipartFile imgfile) throws IOException {

        // 输出日志，表示正在执行当前方法FurnitureController.updatefurnitureact

        logger.debug("FurnitureController.updatefurnitureact ......");

// 判断图片文件是否为空  

        if (!imgfile.isEmpty()) {

// 调用uploadUtile方法将页面传入的图片文件上传到服务器，将返回的文件名保存到img参数中  

            String img = uploadUtile(imgfile, request);

// 将furniture的图片设置为img的值  

            furniture.setImg(img);

        }


        // 执行furnituredao的updateByPrimaryKeySelective方法，将传入的家具数据同步到数据库中

        furnituredao.updateByPrimaryKeySelective(furniture);


        // 将修改成功信息保存到request中

        request.setAttribute("message", "修改家具信息成功");


    } // 定义updatefurnitureactjson处理家具修改

    public void updatefurnitureactjson(Furniture furniture) throws IOException {

        // 输出日志，表示正在执行当前方法FurnitureController.updatefurnitureactjson

        logger.debug("FurnitureController.updatefurnitureactjson ......");

        // 执行furnituredao的updateByPrimaryKeySelective方法，将传入的家具数据同步到数据库中

        furnituredao.updateByPrimaryKeySelective(furniture);

    }


    // 定义deletefurniture,处理删除家具

    public void deletefurniture(HttpServletRequest request, HttpSession session, int id) {

        // 输出日志，表示当前正在执行FurnitureService.deletefurniture方法

        logger.debug("FurnitureService.deletefurniture ......");

        //如果传入的id为-1，表示进行批量删除
        if (id == -1) {
            //实例化家具example
            FurnitureExample example = new FurnitureExample();
            //获取到传递过来的ids数据信息
            String ids = request.getParameter("ids");
            //为id信息添加-1数据，添加此数据可以防止数据为空时的报错
            ids += "-1,";
            //截取掉多余的逗号
            ids.substring(0, ids.length() - 1);
            //设置where语句进行删除id数据的传入
            //example.setWhere("id in ("+ ids +")");
            //实例化家具criteria
            FurnitureExample.Criteria criteria = example.createCriteria();
            //设置integer类型的数组，保存需要删除的家具id信息
            List<Integer> idlist = new ArrayList();
            //根据id分离出需要删除的数据id信息
            String[] idarr = ids.split(",");
            //将对应的id数据信息保存到数组中
            for (int i = 0; i < idarr.length; i++) {
                //取出对应的id信息，并转换成int类型
                idlist.add(Integer.parseInt(idarr[i]));
            }
            //传入需要删除的id数组信息
            criteria.andIdIn(idlist);
            //调用家具的dao类，执行批量删除操作
            furnituredao.deleteByExample(example);
        } else {
            // 根据id调用furnituredao的deleteByPrimaryKey方法，删除家具


            furnituredao.deleteByPrimaryKey(id);

        }


        request.setAttribute("message", "删除家具成功");


    }


    // 定义searchfurniture方法，处理搜索操作

    public void searchfurniture(HttpServletRequest request, HttpSession session, String search) {

        // 输出日志，表示当前正在执行FurnitureService.searchfurniture

        logger.debug("FurnitureService.searchfurniture ......");


        // 实例化 FurnitureExample

        FurnitureExample example = new FurnitureExample();

        // 实例化 FurnitureExample的Criteria内部类

        FurnitureExample.Criteria criteria = example.createCriteria();

        // 如果搜索内容不等于空

        if (search != null) {

            // 将搜索内容通过like关键字传到数据库中进行搜索

            criteria.andNameLike("%" + search + "%");

        }

        // 查询家具结果

        List furnitureall = furnituredao.selectByExample(example);

        // 将查询到的家具 保存到request中进行保存

        request.setAttribute("furnitureall", furnitureall);

    }


    // 定义searchfurniturejson方法，处理搜索操作

    public Map searchfurniturejson(String search) {

        // 输出日志，表示当前正在执行FurnitureService.searchfurniturejson

        logger.debug("FurnitureService.searchfurniturejson ......");

        // 定义返回结果

        Map result = new HashMap();

        // 实例化 FurnitureExample

        FurnitureExample example = new FurnitureExample();

        // 实例化 FurnitureExample的Criteria内部类

        FurnitureExample.Criteria criteria = example.createCriteria();

        // 如果搜索内容不等于空

        if (search != null) {

            // 将搜索内容通过like关键字传到数据库中进行搜索

            criteria.andNameLike("%" + search + "%");

        }

        // 查询家具结果

        List furnitureall = furnituredao.selectByExample(example);

        // 将查询到的家具 保存到request中进行保存

        result.put("furnitureall", furnitureall);

        // 返回查询结果resultmap

        return result;

    }


    // 定义FurniturepinglunMapper

    public void furnituredetails(HttpServletRequest request, HttpSession session, int id) {

        // 输入日志信息，表名当前执行方法为FurnitureController.furnituredetails

        logger.debug("FurnitureController.furnituredetails ......");


        // 传入页面所传入的家具id使用furnituredao的selectByPrimaryKey方法进行查询

        Furniture furniture = furnituredao.selectByPrimaryKey(id);

        // 将查询到的家具保存到request中

        request.setAttribute("furniture", furniture);


        // 实例化FurniturepinglunExample

        FurniturepinglunExample example = new FurniturepinglunExample();
        FurniturepinglunExample.Criteria criteria = example.createCriteria();
        criteria.andFurnitureidEqualTo(id); // 使用furniturepinglundao的selectByExample方法查询furniturepinglunall

        List furniturepinglunall = furniturepinglundao.selectByExample(example);

        // 将furniturepinglunall保存到request中

        request.setAttribute("furniturepinglunall", furniturepinglunall);

    }


    // 定义Furniture详情方法

    public Map furnituredetailsjson(int id) {

        // 输入日志信息，表名当前执行方法为FurnitureController.furnituredetailsjson

        logger.debug("FurnitureController.furnituredetailsjson ......");


        // 定义返回结果

        Map result = new HashMap();

        // 传入页面所传入的家具id使用furnituredao的selectByPrimaryKey方法进行查询

        Furniture furniture = furnituredao.selectByPrimaryKey(id);

        // 将查询到的家具保存到result中

        result.put("furniture", furniture);


        // 实例化Furniture评论详情

        FurniturepinglunExample example = new FurniturepinglunExample();
        FurniturepinglunExample.Criteria criteria = example.createCriteria();
        criteria.andFurnitureidEqualTo(id); // 使用furniturepinglundao的selectByExample方法查询furniturepinglunall

        List furniturepinglunall = furniturepinglundao.selectByExample(example);

        // 将furniturepinglunall保存到resilt中

        result.put("furniturepinglunall", furniturepinglunall);

        // 返回查询结果resultmap

        return result;

    }


//	上传文件图片等

    public String uploadUtile(MultipartFile file, HttpServletRequest request) throws IOException {

        // 根据当前时间生成时间字符串

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");

        String res = sdf.format(new Date());

        // uploads文件夹位置

        String tomcatroot = request.getSession().getServletContext().getRealPath("resource/uploads/");
        String localroot = request.getServletContext().getRealPath("").split("out")[0] + "WebRoot/resource/uploads";
        System.out.println(tomcatroot);
        System.out.println(localroot);

        // 原始名称

        String originalFileName = file.getOriginalFilename();

        // 新文件名

        String newFileName = "sliver" + res + originalFileName.substring(originalFileName.lastIndexOf("."));

        // 创建年月文件夹

        Calendar date = Calendar.getInstance();

        File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1));

        // 新文件

        File tomcatFile = new File(tomcatroot + File.separator + dateDirs + File.separator + newFileName);
        File localFile = new File(localroot + File.separator + dateDirs + File.separator + newFileName);

        // 判断目标文件所在目录是否存在

        if (!tomcatFile.getParentFile().exists()) {

            // 如果目标文件所在的目录不存在，则创建父目录

            tomcatFile.getParentFile().mkdirs();

        }
        // 判断目标文件所在目录是否存在

        if (!localFile.getParentFile().exists()) {

            // 如果目标文件所在的目录不存在，则创建父目录

            localFile.getParentFile().mkdirs();

        }

        file.transferTo(tomcatFile);

        String fileUrl = date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH) + 1) + "/" + newFileName;

        return fileUrl;

    }
}

